// M.doSql=M.Db().doSql

let dictory_tableName="mi_dictionary";

let Db=M.Db()

app.begin(req=>{
    console.log("app.begin",req.pureUrl,req.params)
})

app.get("/miApiListByPage",function (req,res) {
    let whereCase="1=1 ";
    if(req.params.name){
        whereCase=whereCase+` and name like '%${req.params.name}%'`
    }
    if(req.params.parent_id){
        whereCase=whereCase+` and parent_id = '${req.params.parent_id}'`
    }
    const sql1=` 
    select *  from  ${dictory_tableName}  where ${whereCase}  limit  ${(req.params.startPage-1)*req.params.limit},${req.params.limit}`
   const sql2= `
        select count(1) c from ${dictory_tableName}  where ${whereCase};
    `;
    M.doSql(sql1).then((d) => {
        let rows = d.data;
        M.doSql(sql2).then((d) => {
            let total = d.data[0].c; 
            res.send({rows ,total});
        });
    })
});


app.post("/miApiAdd",async function (req,res) {
    let miApi=req.params;

    if(!miApi.parent_id){
        miApi.parent_id=-1;
    }

    let sql =` 
    insert into ${dictory_tableName}(parent_id,name,query_code,use_code,gmt_create,gmt_modify) values ('${miApi.parent_id}','${miApi.name}','${miApi.query_code}','${miApi.use_code}',NOW(),NOW());
    ` 

    M.doSql(sql).then(d=>{
        res.send("ok");
    })
});

app.post("/miApiUpdate",function (req,res) {
    let miApi=req.params;
    delete miApi.leaf;
    let sql =` 
    update ${dictory_tableName} set name='${miApi.name}',query_code='${miApi.query_code}',use_code='${miApi.use_code}',gmt_modify=now() where id=${miApi.id};
      ` 
    M.doSql(sql).then(d=>{
        res.send("ok");
    })
});


app.get("/miApiDelete",async function (req,res) {
    let id=req.params.id;
     let sql=`
                delete from 
                ${dictory_tableName}
                WHERE 
                id
                in
                (
                    select id from (
                    select t1.id,
                    if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild
                    from (
                            select id,parent_id from ${dictory_tableName} 
                            ) t1,
                            (select @pids := ${id}) t2
                    ) t3 where ischild != 0
                    union
                    SELECT ${id} from DUAL
                )
     `;
    M.doSql(sql).then(async d=>{
         res.send("ok");
    })
});




